#ifdef _WIN32
#include "win_type.h"

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <minwinbase.h>
#include <stdio.h>
#include <stdlib.h>

struct pthread_mutex_t 
{
	CRITICAL_SECTION section;
};

void usleep(int x) 
{
	Sleep(x / 1000);
}

int pthread_create(pthread_t* pid, void* attr, thread_proc proc, void* object) 
{
	(*pid) = CreateThread(NULL, 0, (PTHREAD_START_ROUTINE)proc, object, 0, NULL);
	return 0;
}

void pthread_join(pthread_t pid, void* attr)
{
	WaitForSingleObject(pid, INFINITE);
	CloseHandle(pid);
}

void pthread_cond_init(pthread_cond_t* handle)
{
	(*handle) = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (!(handle)) {
		printf("CreateEvent failed\n");
	}
}

void pthread_cond_signal(pthread_cond_t* handle)
{
	SetEvent((*handle));
	//PulseEvent(*(handle));
}

void pthread_cond_wait(pthread_cond_t* handle)
{
	WaitForSingleObject((*handle), INFINITE);
}

void pthread_cond_destroy(pthread_cond_t* handle)
{
	if (handle) {
		CloseHandle((*handle));
	}
}

void pthread_mutex_init(struct pthread_mutex_t** lock, void* x)
{
	(*lock) = (struct pthread_mutex_t*)malloc(sizeof(struct pthread_mutex_t));
	InitializeCriticalSection(&((*lock)->section));
}

void pthread_mutex_lock(struct pthread_mutex_t*lock)
{
	EnterCriticalSection(&(lock->section));
}

void pthread_mutex_unlock(struct pthread_mutex_t* lock)
{
	LeaveCriticalSection(&(lock->section));
}

void pthread_mutex_destroy(struct pthread_mutex_t* lock)
{
	DeleteCriticalSection(&(lock->section));
	free(lock);
}

#endif

